package com.example.train_operate.util;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;

@Component
public class JwtUtil {
    public static final String SECRET = "5Kb8kLf9zgWQnogidDA76MzPL6TsZ";


    public static String createToken(int id) {
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.HOUR,7);
        JWTCreator.Builder builder = JWT.create();
        String token = builder.withAudience(new String[]{String.valueOf(id)}).withExpiresAt(instance.getTime()).sign(Algorithm.HMAC256(SECRET));
        return token;
    }

    public static DecodedJWT verify(String token) {
        return JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
    }

    public static Integer getUser() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String authorization = request.getHeader("Authorization");
        int userId = Integer.parseInt((String)JWT.decode(authorization).getAudience().get(0));
        return userId;
    }
}
